<template>
  <div class="outer-container">
    <div class="container">
      <div class="login-container">
        <div class="header">
          <div class="icon-box">
            <div class="pulse"></div>
            <el-icon class="beat">
              <svg
                xmlns="http://www.w3.org/2000/svg"
                viewBox="0 0 24 24"
                fill="none"
                stroke="currentColor"
                stroke-width="2"
                stroke-linecap="round"
                stroke-linejoin="round"
              >
                <path
                  d="M20.84 4.61a5.5 5.5 0 0 0-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 0 0-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 0 0 0-7.78z"
                ></path>
              </svg>
            </el-icon>
          </div>
        </div>
        <h1>欢迎登录</h1>
        <p class="subtitle">心理健康管理系统平台</p>
        <el-form @submit.prevent="handleLogin" :model="loginForm" ref="loginFormRef" :rules="rules">
          <el-form-item prop="username">
            <el-input
              v-model="loginForm.username"
              placeholder="账号"
              :prefix-icon="User"
              autocomplete="off"
              class="rounded-input"
            />
          </el-form-item>
          <el-form-item prop="password">
            <el-input
              v-model="loginForm.password"
              placeholder="密码"
              :type="passwordVisible ? 'text' : 'password'"
              :prefix-icon="Lock"
              class="rounded-input"
            >
              <template #suffix>
                <span
                  v-if="loginForm.password"
                  class="custom-password-toggle"
                  @mousedown.prevent="togglePasswordVisibility"
                >
                  <el-icon>
                    <component :is="passwordVisible ? View : Hide" />
                  </el-icon>
                </span>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              native-type="submit"
              class="btn-login"
              :loading="loading"
              round
            >
              {{ loading ? '登录中...' : '登录' }}
            </el-button>
          </el-form-item>
        </el-form>
        <div class="bottom-options">
          <div class="options-left">
            没有账号？<el-link type="primary" @click="toRegister">立即注册</el-link>
          </div>
          <div class="options-right">
            忘记密码？<el-link type="primary" @click="toForgotPassword">找回密码</el-link>
          </div>
        </div>
        <div class="copyright">
          版权所有 © {{ new Date().getFullYear() }} 心理健康管理系统 - 保留所有权利
        </div>
      </div>
      <div class="decoration-container">
        <img
          src=""
          class="illustration"
          alt="Psychology Illustration"
        />
        <div class="motto">
          <h3>心灵的港湾，情绪的向导</h3>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { User, Lock, View, Hide } from '@element-plus/icons-vue'
import type { FormInstance } from 'element-plus'
import { login } from '@/api/user'
import { useUserStore } from '@/stores/user'

const router = useRouter()
const userStore = useUserStore()
const loginFormRef = ref<FormInstance>()
const loading = ref(false)
const passwordVisible = ref(false)

const loginForm = reactive({
  username: '',
  password: '',
})

const rules = {
  username: [
    { required: true, message: '请输入账号', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' },
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' },
  ],
}

const togglePasswordVisibility = () => {
  passwordVisible.value = !passwordVisible.value
}

const handleLogin = async () => {
  if (!loginFormRef.value) return

  await loginFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      try {
        loading.value = true
        const res = await login({
          userName: loginForm.username,
          accountId: loginForm.username,
          password: loginForm.password,
        })

        // 检查响应数据中是否包含token
        if (!res.data || !res.data.token) {
          console.error('登录响应缺少token:', res)
          ElMessage.error('登录失败：未获取到token')
          return
        }

        // 存储用户信息到Pinia store
        userStore.setUserInfo(res.data)

        // 也存储到localStorage以便请求拦截器使用
        localStorage.setItem('token', res.data.token)
        localStorage.setItem('userRole', res.data.role || '')
        localStorage.setItem('userName', res.data.userName || loginForm.username)
        localStorage.setItem('accountId', loginForm.username)

        console.log('登录成功，已获取token:', res.data.token)

        ElMessage.success('登录成功')

        // 检查是否有重定向地址
        const redirectPath = localStorage.getItem('redirect')
        if (redirectPath) {
          localStorage.removeItem('redirect')
          router.push(redirectPath)
        } else {
          router.push('/home')
        }
      } catch (error: any) {
        console.error('登录失败', error)

        // 获取并显示更详细的错误信息
        let errorMsg = '登录失败，请重试'
        if (error.response && error.response.data) {
          errorMsg = error.response.data.msg || errorMsg
        }

        ElMessage.error(errorMsg)
      } finally {
        loading.value = false
      }
    }
  })
}

const toRegister = () => {
  router.push('/register')
}

const toForgotPassword = () => {
  router.push('/forgot-password')
}
</script>

<style scoped>
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: 'Microsoft YaHei', sans-serif;
}

.outer-container {
  min-height: 100vh;
  background: #4086f4;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 20px;
  width: 100%;
  position: absolute;
  top: 0;
  left: 0;
}

.container {
  width: 90%;
  max-width: 1100px;
  background: #fff;
  border-radius: 16px;
  box-shadow: 0 20px 60px rgba(0, 0, 0, 0.15);
  overflow: hidden;
  position: relative;
  margin: 0 auto;
  display: flex;
  flex-direction: row-reverse;
}

.login-container {
  width: 480px;
  padding: 60px;
  position: relative;
  z-index: 1;
  background: #fff;
  display: flex;
  flex-direction: column;
}

.header {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-bottom: 60px;
}

.icon-box {
  width: 64px;
  height: 64px;
  background-color: #f6f9ff;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
  overflow: hidden;
}

.icon-box svg {
  width: 32px;
  height: 32px;
  color: #4086f4;
}

.pulse {
  position: absolute;
  width: 100%;
  height: 100%;
  border-radius: 50%;
  background-color: rgba(64, 134, 244, 0.1);
  transform: scale(1);
  animation: pulse 2s infinite;
}

@keyframes pulse {
  0% {
    transform: scale(0.95);
    opacity: 0.7;
  }
  50% {
    transform: scale(1.05);
    opacity: 0.3;
  }
  100% {
    transform: scale(0.95);
    opacity: 0.7;
  }
}

@keyframes beat {
  0% {
    transform: scale(1);
  }
  15% {
    transform: scale(1.15);
  }
  30% {
    transform: scale(1);
  }
  45% {
    transform: scale(1.15);
  }
  60% {
    transform: scale(1);
  }
  100% {
    transform: scale(1);
  }
}

.beat {
  animation: beat 2s infinite;
  transform-origin: center;
}

h1 {
  font-size: 24px;
  color: #333;
  margin-bottom: 8px;
  font-weight: normal;
  text-align: center;
}

.subtitle {
  color: #999;
  font-size: 14px;
  margin-bottom: 40px;
  text-align: center;
}

/* 表单样式修改 */
.el-form {
  width: 100%;
}

.el-form-item {
  margin-bottom: 20px;
}

.rounded-input :deep(.el-input__wrapper) {
  border-radius: 20px;
  box-shadow: 0 0 0 1px #dcdfe6 inset;
}

.rounded-input :deep(.el-input__wrapper.is-focus) {
  box-shadow: 0 0 0 1px #4086f4 inset;
}

.custom-password-toggle {
  cursor: pointer;
  font-size: 16px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #909399;
  margin-right: 4px;
}

.custom-password-toggle:hover {
  color: #4086f4;
}

.btn-login {
  width: 100%;
  height: 40px;
  background: #4086f4;
  border: none;
  border-radius: 20px;
  color: white;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s;
}

.btn-login:hover {
  background: #3076e4;
}

.btn-login:disabled {
  background-color: #94bbf9;
  cursor: not-allowed;
}

.decoration-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background: linear-gradient(45deg, #ebf3ff 0%, #ffffff 100%);
  position: relative;
  overflow: hidden;
  min-height: 500px;
}

.illustration {
  width: 80%;
  max-width: 500px;
  opacity: 0.9;
}

.bottom-options {
  display: flex;
  justify-content: space-between;
  margin-top: 20px;
  font-size: 12px;
  color: #999;
}

.options-left,
.options-right {
  display: flex;
  align-items: center;
}

.options-left {
  width: 45%;
  justify-content: flex-start;
}

.options-right {
  width: 45%;
  justify-content: flex-end;
}

.bottom-options a {
  color: #4086f4;
  text-decoration: none;
  transition: all 0.3s;
}

.bottom-options a:hover {
  text-decoration: underline;
}

.copyright {
  margin-top: 40px;
  text-align: center;
  color: #999;
  font-size: 12px;
  margin-top: auto;
  padding-top: 20px;
}

.motto {
  margin-top: 40px;
  text-align: center;
  padding: 0 40px;
}

.motto h3 {
  color: #4086f4;
  font-size: 18px;
  font-weight: normal;
  margin-bottom: 10px;
}

@media (max-width: 900px) {
  .login-container {
    width: 100%;
    padding: 40px;
  }

  .decoration-container {
    display: none;
  }
}
</style>
